package com.inxedu.os.edu.service.impl.webpage;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.inxedu.os.common.cache.CacheUtil;
import com.inxedu.os.common.constants.CacheConstans;
import com.inxedu.os.common.constants.CommonConstants;
import com.inxedu.os.common.entity.PageEntity;
import com.inxedu.os.common.util.*;
import com.inxedu.os.edu.constants.enums.WebSiteProfileType;
import com.inxedu.os.edu.dao.webpage.WebpageDao;
import com.inxedu.os.edu.entity.article.Article;
import com.inxedu.os.edu.entity.article.QueryArticle;
import com.inxedu.os.edu.entity.templatedatasource.TemplateDatasource;
import com.inxedu.os.edu.entity.webpage.Webpage;
import com.inxedu.os.edu.entity.webpagetemplate.WebpageTemplate;
import com.inxedu.os.edu.entity.website.WebsiteImages;
import com.inxedu.os.edu.service.article.ArticleService;
import com.inxedu.os.edu.service.templatedatasource.TemplateDatasourceService;
import com.inxedu.os.edu.service.webpage.WebPagePublishThread;
import com.inxedu.os.edu.service.webpage.WebpageService;
import com.inxedu.os.edu.service.webpagetemplate.WebpageTemplateService;
import com.inxedu.os.edu.service.website.WebsiteImagesService;
import com.inxedu.os.edu.service.website.WebsiteNavigateService;
import com.inxedu.os.edu.service.website.WebsiteProfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author www.inxedu.com
 * @description 页面 WebpageService接口实现
 */
@Service("webpageService")
public class WebpageServiceImpl implements WebpageService {
	@Autowired
	private WebpageDao webpageDao;
	@Autowired
	private WebpageTemplateService webpageTemplateService;
	@Autowired
	private WebsiteProfileService websiteProfileService;
    @Autowired
    private WebsiteImagesService websiteImagesService;
    @Autowired
    private WebsiteNavigateService websiteNavigateService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private TemplateDatasourceService templateDatasourceService;
	/**
     * 添加页面
     */
    public Long addWebpage(Webpage webpage){
		return webpageDao.addWebpage(webpage);
    }
    
    /**
     * 删除页面
     * @param id
     */
    public void delWebpageById(Long id){
    	webpageDao.delWebpageById(id);
    }
    
    /**
     * 修改页面
     * @param webpage
     */
    public void updateWebpage(Webpage webpage){
    	webpageDao.updateWebpage(webpage);
    }
    
    /**
     * 通过id，查询页面
     * @param id
     * @return
     */
    public Webpage getWebpageById(Long id){
    	return webpageDao.getWebpageById(id);
    }
    
    /**
     * 分页查询页面列表
     * @param webpage 查询条件
     * @param page 分页条件
     * @return List<Webpage>
     */
    public List<Webpage> queryWebpageListPage(Webpage webpage,PageEntity page){
    	return webpageDao.queryWebpageListPage(webpage, page);
    }
    
    /**
     * 条件查询页面列表
     * @param webpage 查询条件
     * @return List<Webpage>
     */
    public List<Webpage> queryWebpageList(Webpage webpage){
    	return webpageDao.queryWebpageList(webpage);
    }

    @Override
    public Map<String,String> updWebpagePublish(Long id, String rootpath) throws Exception{
        Map<String,String> map = new HashMap();
        Webpage webpage = this.getWebpageById(id);

        WebpageTemplate webpageTemplate=new WebpageTemplate();
        webpageTemplate.setPageId(webpage.getId());
        webpageTemplate.setEffective(1);//是否生效 1生效（默认） 2预览（新增的为2，预览查看所有，发布只查询1的，正式发布后修改为1）
        List<WebpageTemplate> webpageTemplateList=webpageTemplateService.queryWebpageTemplateList(webpageTemplate);
        /*判断如果不是首页*/
        if (!"/index.html".equals(webpage.getPublishUrl())){
            /*获取首页的页面信息*/
            Webpage webpage1 = new Webpage();
            webpage1.setPublishUrl("/index.html");
            webpage1 = this.queryWebpageList(webpage1).get(0);
            /*获取首页的模板信息*/
            WebpageTemplate webpageTemplate1 = new WebpageTemplate();
            webpageTemplate1.setPageId(webpage1.getId());
            webpageTemplate1.setEffective(1);
            /*首页的模板信息*/
            List<WebpageTemplate> indexTemplates = webpageTemplateService.queryWebpageTemplateList(webpageTemplate1);
            /*首页的头模板*/
            WebpageTemplate header = indexTemplates.get(0);
            /*首页的脚模板*/
            WebpageTemplate fotter = indexTemplates.get(indexTemplates.size()-1);
            /*替换要发布的模板的头尾为首页头尾*/
            webpageTemplateList.remove(0);
            webpageTemplateList.add(0,header);
            webpageTemplateList.remove(webpageTemplateList.size()-1);
            webpageTemplateList.add(fotter);
        }

        Map<String, Object> root = this.getTemplateRootMap(webpage);

        /* ftl文件名*/
        String publishUrl = StringUtils.isNotEmpty(webpage.getPublishUrl())?webpage.getPublishUrl():"";
        publishUrl=rootpath+publishUrl;
        String ftlName = publishUrl;
        ftlName = ftlName.substring(ftlName.lastIndexOf("/")+1,ftlName.lastIndexOf("."));
        //生成模板路径
        String ftlUrl=rootpath+"/WEB-INF/ftl";
        if(ObjectUtils.isNotNull(webpageTemplateList)){
            StringBuffer bodyHtml=new StringBuffer();
            for (WebpageTemplate webpageTemplateTemp:webpageTemplateList){
                bodyHtml.append(FileUtils.readLineFile(rootpath.replace("\\","/")+webpageTemplateTemp.getTemplateUrl())
                        .replace("TEMPLATE_TITLE","TEMPLATE_TITLE"+webpageTemplateTemp.getId())
                        .replace("TEMPLATE_INFO","TEMPLATE_INFO"+webpageTemplateTemp.getId())
                        .replace("WEBSITE_IMAGES_LIST","WEBSITE_IMAGES_LIST"+webpageTemplateTemp.getId())
                        .replace("TEMPLATE_ID","TEMPLATE_ID"+webpageTemplateTemp.getId())//模板id 用于分页
                        .replace("TEMPLATE_LABEL_","TEMPLATE_LABEL_"+webpageTemplateTemp.getId())//TEMPLATE_LABEL_ 模板标签id
                        .replace("selectPageId",webpage.getId()+"")//右侧更换页面选中状态
                );

                //模板数据填充
                root.put("TEMPLATE_TITLE"+webpageTemplateTemp.getId(), webpageTemplateTemp.getTemplateTitle());
                root.put("TEMPLATE_INFO"+webpageTemplateTemp.getId(), webpageTemplateTemp.getInfo());

                WebsiteImages websiteImages=new WebsiteImages();
                websiteImages.setWebpageTemplateId(webpageTemplateTemp.getId());
                websiteImages.setQueryOrder("queryAsc");
                List<WebsiteImages> websiteImagesList=websiteImagesService.queryImageList(websiteImages);
                root.put("WEBSITE_IMAGES_LIST"+webpageTemplateTemp.getId(), websiteImagesList);
            }
            //root.put("body", bodyHtml.toString());
            FileUtils.writeFile(ftlUrl+"/"+ftlName+".ftl",bodyHtml.toString());
        }
        String dicPath = publishUrl.substring(0,publishUrl.lastIndexOf("/"));
        while (!dicPath.equals(rootpath)){
            dicPath = dicPath.substring(0,dicPath.lastIndexOf("/"));
            File file = new File(publishUrl.substring(0,publishUrl.lastIndexOf("/")));
            if (file.exists()&&!file.isDirectory()){
                map.put("success","false");
                map.put("message","存在与文件夹名称相同的文件");
                return  map;
            }
        }

        FileUtils.createPath(publishUrl.substring(0,publishUrl.lastIndexOf("/")));
        FileUtils.createFile(publishUrl);
        //根据生成的模板 发布页面
        FreeMarkerUtil.analysisTemplate(ftlUrl,ftlName+".ftl",publishUrl,root);
        map.put("success","true");
        return map;
    }


    /**
     * 模板 root 数据
     * @return
     */
    public Map<String, Object> getTemplateRootMap(Webpage webpage){
        Map<String, Object> root = new HashMap<>();
        //获得网站配置
        Map<String,Object> webmap=(Map<String,Object>)websiteProfileService.getWebsiteProfileByType(WebSiteProfileType.web.toString()).get(WebSiteProfileType.web.toString());

        if(StringUtils.isEmpty(webpage.getTitle())){
            root.put("title", webmap.get("title").toString());
        }else {
            root.put("title", webpage.getTitle());
        }
        if(StringUtils.isEmpty(webpage.getAuthor())){
            root.put("author", webmap.get("author").toString());
        }else {
            root.put("author", webpage.getAuthor());
        }
        if(StringUtils.isEmpty(webpage.getKeywords())){
            root.put("keywords", webmap.get("keywords").toString());
        }else {
            root.put("keywords", webpage.getKeywords());
        }
        /*网站尾部信息*/
        root.put("webmap", webmap);
        if(StringUtils.isEmpty(webpage.getDescription())){
            root.put("description", webmap.get("description").toString());
        }else {
            root.put("description", webpage.getDescription());
        }
        /*rootPath*/
        //root.put("rootPath",request.getSession().getServletContext().getRealPath("/"));
         /*groupPath*/
        //root.put("groupPath",CommonConstants.groupPath);
        /*ctx*/
        root.put("ctx",CommonConstants.contextPath);
        /*webUrl*/
        root.put("webUrl",CommonConstants.webUrl);
   /*     *//*获取banner图*//*
        WebsiteImages websiteImages = new WebsiteImages();
        websiteImages.setTypeId(1);
        PageEntity page = new PageEntity();
        page.setPageSize(10);
        List<Map<String,Object>> bannerImgs = websiteImagesService.queryImagePage(websiteImages,page);
        root.put("bannerImgs",bannerImgs);*/
        /*首页导航*/
        Map<String,Object> navigatemap = websiteNavigateService.getWebNavigate();
        root.put("websiteNavigates",navigatemap.get("INDEX"));
        root.put("friendLink",navigatemap.get("FRIENDLINK"));
     /*   *//*从网校获取首页的教师信息*//*
        root.put("teachers",getTemplateDataByKey("teachers"));
         *//*从网校获取8条名师信息*//*
        root.put("teacherTeam",getTemplateDataByKey("teacherTeam"));
          *//*从网校获取5条名师信息*//*
        root.put("teacherTeamFive",getTemplateDataByKey("teacherTeamFive"));*/

        /*从网校获取6条精品课程信息*/
        root.put("course",getTemplateDataByKey("course"));
         /*从网校获取8条精品课程信息*/
        root.put("goodCourse",getTemplateDataByKey("goodCourse"));
         /*从网校获取全部课程信息*/
        root.put("allCourse",getTemplateDataByKey("allCourse"));
       /*从网校获取最新课程信息*/
        root.put("newCourse",getTemplateDataByKey("newCourse"));
        /*获取4条首页热度资讯*/
        List<Article> article =  newArticles(4);
        root.put("article",article);
         /*获取6条资讯排行信息*/
        List<Article> articleRecommend =  newArticles(6);
        root.put("articleRecommend",articleRecommend);
        /*从社区获取热门话题*/
        root.put("groupHotTopicList",getTemplateDataByKey("groupHotTopicList"));
          /*从网校获5条资讯排行信息*/
        root.put("articleRecommendFive",getTemplateDataByKey("articleRecommendFive"));
        /*从网校获取8条资讯列表*/
        List<Article> articleList =  newArticles(8);
        root.put("articleList",articleList);
        /*从网校获取10条资讯列表*/
        List<Article> articleList10 =  newArticles(10);

        root.put("articleList10",articleList10);
        root.put("body", "");//设置空值
        return root;
    }
    /*按按热查询资讯信息*/
    public List<Article> hotArticles(int pageSize){
        QueryArticle queryArticle = new QueryArticle();
        queryArticle.setType(2);
        PageEntity page = new PageEntity();
        page.setPageSize(pageSize);
        List<Article> articleList = articleService.queryArticlePage(queryArticle, page);
        return articleList;
    }
    /*度时间查询咨询信息*/
    public List<Article> newArticles(int pageSize){
        QueryArticle query = new QueryArticle();
        query.setType(2);
        query.setCount(pageSize);
        query.setOrderby(1);
        List<Article>articleList = articleService.queryArticleList(query);
        return articleList;
    }
    /**
     * 通过数据 key 获取数据
     * @param dataKey
     * @return
     */
    public Object getTemplateDataByKey(String dataKey) {
        Map<String,Object> template_data= (Map<String, Object>) CacheUtil.get(CacheConstans.TEMPLATE_DATA);
        template_data = null;
        if(ObjectUtils.isNull(template_data)){
            template_data=new HashMap<String, Object>();
            List<TemplateDatasource> templateDatasourceList=templateDatasourceService.queryTemplateDatasourceList(null);
            if(ObjectUtils.isNotNull(templateDatasourceList)){
                for (TemplateDatasource templateDatasource:templateDatasourceList){
                    String url=CommonConstants.webUrl;
                    if (StringUtils.isNotEmpty(url)){
                        String data ="";
                        data = HttpUtil.doPost(url+templateDatasource.getDataUrl(),null);
                        Map<String,Object> resultMap=new Gson().fromJson(data, new TypeToken<Map<String,Object>>(){}.getType());
                        if (ObjectUtils.isNotNull(resultMap)){
                            template_data.put(templateDatasource.getDataKey(),resultMap.get("entity"));
                        }
                    }
                }
            }

            /*从网校获取首页的教师信息*//*
            String teachers = HttpUtil.doPost(CommonConstants.webUrl+"/webapp/teacherList",null);
            Map<String,Object> resultMap=new Gson().fromJson(teachers, new TypeToken<Map<String,Object>>(){}.getType());
            template_data.put("teachers",resultMap.get("entity"));
            *//*从网校获取8条名师信息*//*
            String teacherTeam = HttpUtil.doPost(CommonConstants.webUrl+"/webapp/teacherTeamList?num=8",null);
            Map<String,Object> resultTeacherMap=new Gson().fromJson(teacherTeam, new TypeToken<Map<String,Object>>(){}.getType());
            template_data.put("teacherTeam",resultTeacherMap.get("entity"));
            *//*从网校获取5条名师信息*//*
            String teacherTeamFive = HttpUtil.doPost(CommonConstants.webUrl+"/webapp/teacherTeamList?num=5",null);
            Map<String,Object> resultTeacherFiveMap=new Gson().fromJson(teacherTeamFive, new TypeToken<Map<String,Object>>(){}.getType());
            template_data.put("teacherTeamFive",resultTeacherFiveMap.get("entity"));
            *//*从网校获取6条精品课程信息*//*
            String course = HttpUtil.doPost(CommonConstants.webUrl+"/webapp/courseList?num=6",null);
            Map<String,Object> courseMap = new Gson().fromJson(course,new TypeToken<Map<String,Object>>(){}.getType());
            template_data.put("course",courseMap.get("entity"));
            *//*从网校获取8条精品课程信息*//*
            String goodCourse = HttpUtil.doPost(CommonConstants.webUrl+"/webapp/courseList?num=8",null);
            Map<String,Object> goodCourseMap = new Gson().fromJson(goodCourse,new TypeToken<Map<String,Object>>(){}.getType());
            template_data.put("goodCourse",goodCourseMap.get("entity"));
            *//*从网校获取全部课程信息*//*
            String allCourse = HttpUtil.doPost(CommonConstants.webUrl+"/webapp/typeCourse?order=ALL",null);
            Map<String,Object> allCourseMap = new Gson().fromJson(allCourse,new TypeToken<Map<String,Object>>(){}.getType());
            template_data.put("allCourse",allCourseMap.get("entity"));
            *//*从网校获取最新课程信息*//*
            String newCourse = HttpUtil.doPost(CommonConstants.webUrl+"/webapp/typeCourse?order=NEW",null);
            Map<String,Object> newCourseMap = new Gson().fromJson(newCourse,new TypeToken<Map<String,Object>>(){}.getType());
            template_data.put("newCourse",newCourseMap.get("entity"));
            *//*从网校获取4条首页资讯*//*
            String articleImg = HttpUtil.doPost(CommonConstants.webUrl+"/webapp/article?size=4",null);
            Map<String,Object> article = new Gson().fromJson(articleImg,new TypeToken<Map<String,Object>>(){}.getType());
            template_data.put("article",article.get("entity"));
            *//*从网校获取6条首页资讯信息*//*
            String articleContent = HttpUtil.doPost(CommonConstants.webUrl+"/webapp/article?size=6",null);
            Map<String,Object> ac = new Gson().fromJson(articleContent,new TypeToken<Map<String,Object>>(){}.getType());
            template_data.put("articleContent",ac.get("entity"));
            *//*从网校获6条资讯排行信息*//*
            String articleRecommend = HttpUtil.doPost(CommonConstants.webUrl+"/webapp/recommend?num=6",null);
            Map<String,Object> ar = new Gson().fromJson(articleRecommend,new TypeToken<Map<String,Object>>(){}.getType());
            template_data.put("articleRecommend",ar.get("entity"));
            *//*从社区获取热门话题*//*
            String hotTopic = HttpUtil.doPost(CommonConstants.groupPath+"/groupApp/groupHotTopic",null);
            Map<String,Object> hotTopicMap = new Gson().fromJson(hotTopic,new TypeToken<Map<String,Object>>(){}.getType());
            template_data.put("groupHotTopicList",hotTopicMap.get("groupHotTopicList"));
            *//*从网校获5条资讯排行信息*//*
            String articleRecommendFive = HttpUtil.doPost(CommonConstants.webUrl+"/webapp/recommend?num=6",null);
            Map<String,Object> arF = new Gson().fromJson(articleRecommendFive,new TypeToken<Map<String,Object>>(){}.getType());
            template_data.put("articleRecommendFive",arF.get("entity"));
            *//*从网校获取8条资讯列表*//*
            String articleList = HttpUtil.doPost(CommonConstants.webUrl+"/webapp/article?size=8",null);
            Map<String,Object> al = new Gson().fromJson(articleList,new TypeToken<Map<String,Object>>(){}.getType());
            template_data.put("articleList",al.get("entity"));
            *//*从网校获取10条资讯列表*//*
            String articleList10 = HttpUtil.doPost(CommonConstants.webUrl+"/webapp/article?size=10",null);
            Map<String,Object> al10 = new Gson().fromJson(articleList10,new TypeToken<Map<String,Object>>(){}.getType());
            template_data.put("articleList10",al10.get("entity"));*/

            CacheUtil.set(CacheConstans.TEMPLATE_DATA,template_data, CacheConstans.TEMPLATE_DATA_TIME);
        }
        return template_data.get(dataKey);
    }


    public void publishAll(boolean isPublishAll,HttpServletRequest request){
        WebPagePublishThread webPagePublishThread = new WebPagePublishThread(this,request.getSession().getServletContext().getRealPath("/"));
        webPagePublishThread.setPublishAll(isPublishAll);
        if (WebPagePublishThread.isPublishIng()==false){
            Thread thread = new Thread(webPagePublishThread);
            thread.start();
        }
    }
}



